package com.imy.luascript.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.imy.common.util.ImageUtils;
import com.imy.common.util.UiUtil;
import com.imy.luascript.R;
import com.imy.luascript.config.GlideApp;


import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;

import jp.wasabeef.glide.transformations.BlurTransformation;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 在此写用途
 *
 * @author: 黄一凡
 * @date: 2017-03-04
 */
public final class GlideUtils {
  public static final int TYPE_BANNER = 1;
  public static final int TYPE_GAME = 2;
  public static final int TYPE_NEWS = 3;
  public static final int TYPE_VIDEO = 4;
  public static final int TYPE_POPCORN = 5;

  private static boolean isHandler;

  /**
   * 加载高速模糊图
   *
   * @param context 上下文
   * @param url 图片地址
   */
  public static void loadBlurImage(Context context, String url, ImageView image) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }
    // “23”：设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”。

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .transition(DrawableTransitionOptions.withCrossFade(1000))
        .error(R.color.colorPrimary)
        .transform(new BlurTransformation(23, 12))
        .into(image);
  }
  public static void loadImage(Context context, String url, SimpleTarget<Bitmap> target){
    if (isActivityDestoryed(context)) {
      return;
    }
    GlideApp.with(context)
            .asBitmap()
            .load(url)
            .format(DecodeFormat.PREFER_ARGB_8888)
            .dontAnimate()
            .into(target);
  }
  public static void loadCircleImage(Context context, ImageView image, String imgUrl) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .asBitmap()
        .load(imgUrl)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .dontAnimate()
        .transform(new CircleCrop())
        .into(image);
  }

  public static RequestBuilder<Drawable> loadCircleImageBuilder(Activity context,
                                                                ImageView image, String imgUrl) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return null;
    }
    return GlideApp.with(context)
        .load(imgUrl)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .dontAnimate()
        .transform(new CircleCrop());
  }






  /**
   * 加载图片
   */
  public static void loadImage(Context context, String url, ImageView image, int type) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }


    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .into(image);
  }

  /**
   * 加载图片（静动态效果+居中裁剪效果）
   */
  public static void loadImageDontAnimateCenterCrop(Context context, String url,
                                                    ImageView image/*, int corner*/) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .asBitmap()
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .dontAnimate()
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .transform(new CenterCrop()/*, new RoundedCorners(context, corner)*/)
        .into(image);
  }

  /**
   * 加载图片
   */
  public static void loadImage(Context context, String url, ImageView image) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .into(image);
  }

  /**
   * 加载图片
   */
  public static void loadImage(Context context, String url, ImageView image, int width,
                               int height) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .override(width, height)
        .into(image);
  }

  /**
   * 加载图片,中间铺满
   */
  public static void loadCenterCropImage(Context context, String url, ImageView image, int width,
                                         int height) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .centerCrop()
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .override(width, height)
        .into(image);
  }

  /**
   * 加载图片
   */
  public static void loadImageWhiteBg(Context context, String url, ImageView image, int width,
                                      int height) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .dontAnimate()
        .placeholder(R.color.white)
        .error(R.color.white)
        .override(width, height)
        .into(image);
  }

  /**
   * 加载圆角图片
   *
   * @param context 上下文
   * @param url 图片地址
   * @param image ImageView控件
   * @param corner 图片圆角角度
   */
  public static void loadRoundCornerImage(Context context, String url, ImageView image, int corner) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .transform(new RoundedCorners(UiUtil.dp2Px(context,corner)))
        .into(image);
  }

  /**
   * 加载图片
   */
  public static void loadImage(Context context, ImageView image, String url, int colorResId,
                               int width, int height) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(colorResId)
        .error(colorResId)
        .override(width, height)
        .into(image);
  }

  /**
   * 加载本地图片 请使用者明确在对应xml有设置宽高
   */
  public static void loadLocalImage(Context context, @DrawableRes int resId, ImageView image) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(resId)
        .format(DecodeFormat.PREFER_RGB_565)
        .into(image);
  }

  private static int[] getSize(int width, int height) {
    int[] size = new int[2];
    if (height >= ImageUtils.getOpenglRenderMaxHeight()) {
      float h = height;
      int s = (int) Math.ceil(h / ImageUtils.getOpenglRenderMaxHeight());
      size[0] = width / s;
      size[1] = height / s;
    } else {
      size[0] = width;
      size[1] = height;
    }
    return size;

  }














  /**
   * 加载网络图片、获得bitmap资源
   */
  public static void loadBitmapResource(Context context, String url, SimpleTarget<Bitmap> target) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .asBitmap()
        .load(url)
        .format(DecodeFormat.PREFER_ARGB_8888)
        .dontAnimate()
        .into(target);
  }

  /**
   * 加载网络图片、获得Drawable资源
   */
  public static void loadDrawableResource(Context context, String url, SimpleTarget<Drawable> target) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_ARGB_8888)
        .dontAnimate()
        .into(target);
  }






  public static void downLoadGif(final  Context context,String url){
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
            //.as(FrameSequenceDrawable.class)//不用FrameSequenceDrawable//友盟报错https://mobile.umeng.com/platform/58eda4807666133957000b0c/error_types/list/3399670601012
            .asGif()
            .format(DecodeFormat.PREFER_ARGB_8888)
            .load(url)
            .diskCacheStrategy(DiskCacheStrategy.DATA)
            .into(new CustomTarget<GifDrawable>() {
              @Override
              public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {

              }

              @Override
              public void onLoadCleared(@Nullable Drawable placeholder) {

              }
            });

            //.skipMemoryCache(true)

  }
  /**
   * 加载挂件
   */
  public static void loadAsGif(final Context context, final ImageView image, String imageUrl) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }
    GlideApp.with(context).clear(image);
    GlideApp.with(context)
        //.as(FrameSequenceDrawable.class)//不用FrameSequenceDrawable//友盟报错https://mobile.umeng.com/platform/58eda4807666133957000b0c/error_types/list/3399670601012
        .asGif()
        .load(imageUrl)
        .format(DecodeFormat.PREFER_RGB_565)
        .placeholder(R.color.whitesmoke)
        .error(R.color.whitesmoke)
        .diskCacheStrategy(DiskCacheStrategy.DATA)
        //.skipMemoryCache(true)
        .into(image);
  }



  public static void loadPendant(final Context context, final ImageView image,
                                 final String imageUrl, RequestListener<Drawable> listener) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context).clear(image);
    GlideApp.with(context)
        .asDrawable()
        .load(imageUrl)
        .diskCacheStrategy(DiskCacheStrategy.DATA)
        .skipMemoryCache(true)
        .listener(listener)
        .into(image);
  }

  /**
   * 清空图片视图。
   */
  public static void clear(ImageView view) {
    if (view == null) {
      return;
    }

    // 尝试修复
    //Caused by: java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    //at com.bumptech.glide.manager.k.c(RequestManagerRetriever.java:323)
    //at com.bumptech.glide.manager.k.a(RequestManagerRetriever.java:132)
    //at com.bumptech.glide.manager.k.a(RequestManagerRetriever.java:116)
    //at com.bumptech.glide.e.c(Glide.java:716)
    //at com.xmcy.hykb.config.a.c(GlideApp.java:88)
    //at com.xmcy.hykb.utils.n.a(GlideUtils.java:1128)
    // 洪顺利 2019-08-29
    Context context = view.getContext();
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context).clear(view);
    view.setImageDrawable(null);
  }

  /**
   * 加载图片
   *
   * @param context 上下文
   * @param image ImageView
   * @param url 图片地址
   * @param colorId 还未加载成功或者失败的默认缺省图颜色值
   */
  public static void loadImage(Context context, ImageView image, String url, @ColorRes int colorId) {
    // 尝试修复 java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
    // 洪顺利 2019-05-29
    if (isActivityDestoryed(context)) {
      return;
    }

    GlideApp.with(context)
        .load(url)
        .format(DecodeFormat.PREFER_RGB_565)
        .dontAnimate()
        .placeholder(colorId)
        .error(colorId)
        .into(image);
  }

  // 尝试修复一下报错 洪顺利 2019-05-29
  // https://mobile.umeng.com/platform/58eda4807666133957000b0c/error_types/list/1887488143012
  //java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
  //at com.bumptech.glide.manager.j.b(RequestManagerRetriever.java:134)
  //at com.bumptech.glide.manager.j.a(RequestManagerRetriever.java:102)
  //at com.bumptech.glide.manager.j.a(RequestManagerRetriever.java:87)
  //at com.bumptech.glide.g.c(Glide.java:629)
  //at com.xmcy.hykb.utils.l.a(GlideUtils.java:518)
  //at com.xmcy.hykb.app.view.CommunityTabBanner.onPageSelected(CommunityTabBanner.java:64)
  //at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1939)
  public static boolean isActivityDestoryed(Context context) {
    boolean result = false;

    if (context == null) {
      result = true;
    }

    if (context instanceof Activity) {
      Activity activity = (Activity) context;

      if (activity.isFinishing()) {
        result = true;
      }

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) {
        result = true;
      }
    }

    return result;
  }

  public static Bitmap decodeSampledBitmap(Bitmap bitmap,
                                           int reqWidth, int reqHeight) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    // 计算缩放比例
    float scaleWidth = ((float) reqWidth) / width;
    float scaleHeight = ((float) reqHeight) / height;
    // 取得想要缩放的matrix参数
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    return Bitmap.createBitmap(bitmap, 0, 0, width, height,
        matrix, true);
  }

  
  /**
   * 加载sd图片
   */
  public static void loadLoaclImageSDCard(final Context context, String localUri, ImageView imageView) {
    if (isActivityDestoryed(context) || TextUtils.isEmpty(localUri)) {
      return;
    }
    GlideApp.with(context)
        .load(new File(localUri))
        .format(DecodeFormat.PREFER_RGB_565)
        .into(imageView);
  }

  /**
   * 加载本地图片 异步 洪顺利  2020-04-24
   */
  public static void loadLoaclImageAsy(final Context context, final String localUri, final OnImageDownloadListener listener) {
    if (isActivityDestoryed(context) || TextUtils.isEmpty(localUri)) {
      return;
    }

    GlideApp.with(context)
        .asBitmap()
        .load(new File(localUri))
        .format(DecodeFormat.PREFER_RGB_565)
        .into(new CustomTarget<Bitmap>() {
          @Override
          public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
            if (listener != null) {
              listener.onSuccess(resource);
            }
          }

          @Override
          public void onLoadFailed(@Nullable Drawable errorDrawable) {
            super.onLoadFailed(errorDrawable);

            if (listener != null) {
              listener.onError();
            }
          }

          @Override
          public void onLoadCleared(@Nullable Drawable placeholder) {

          }
        });
  }

  /**
   * 加载本地图片 同步 洪顺利  2020-04-24
   */
  public static Bitmap loadLoaclImageSyn(final Context context, final String localUri) {
    if (isActivityDestoryed(context) || TextUtils.isEmpty(localUri)) {
      return null;
    }

    Bitmap bitmap = null;

    try {
      bitmap = GlideApp.with(context.getApplicationContext())
          .asBitmap()
          .load(new File(localUri))
          .format(DecodeFormat.PREFER_RGB_565)
          .centerCrop()
          .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
          .get();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return bitmap;
  }

  /**
   * 下载图片 洪顺利  2020-04-24
   */
  public static void downloadImage(final Context context, final String imgUrl, final OnImageDownloadListener listener) {
    GlideApp.with(context.getApplicationContext()).asBitmap().load(imgUrl).into(new CustomTarget<Bitmap>() {
      @Override
      public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
        if (listener != null) {
          listener.onSuccess(resource);
        }
      }

      @Override
      public void onLoadFailed(@Nullable Drawable errorDrawable) {
        super.onLoadFailed(errorDrawable);

        if (listener != null) {
          listener.onError();
        }
      }

      @Override
      public void onLoadCleared(@Nullable Drawable placeholder) {

      }
    });
  }

  public interface OnImageDownloadListener {
    void onSuccess(Bitmap bitmap);

    void onError();
  }
}
